package thrift

import (
	"crypto/tls"
	"fmt"
	"gitee.com/tietang/terrace-go/v2/base"
	"gitee.com/tietang/terrace-go/v2/example/apis/thrift/gen/handlers"
	"github.com/apache/thrift/lib/go/thrift"
)

type ThriftStarter struct {
	base.BaseStarter
}

func (s *ThriftStarter) Init(ctx base.StarterContext) {}
func (s *ThriftStarter) Setup(ctx base.StarterContext) {

}
func (s *ThriftStarter) Start(ctx base.StarterContext) {
	secure := ctx.Props().GetBoolDefault("thrift.secure", false)
	port := ctx.Props().GetDefault("thrift.port", "9091")
	var transport thrift.TServerTransport
	var err error
	if secure {
		cfg := new(tls.Config)
		if cert, err := tls.LoadX509KeyPair("server.crt", "server.key"); err == nil {
			cfg.Certificates = append(cfg.Certificates, cert)
		} else {
			panic(err)
		}
		transport, err = thrift.NewTSSLServerSocket(":"+port, cfg)
	} else {
		transport, err = thrift.NewTServerSocket(":" + port)
	}

	if err != nil {
		panic(err)
	}
	fmt.Printf("%T\n", transport)
	handler := NewAccountServerHandler()
	processor := handlers.NewAccountHandlerProcessor(handler)
	mutiProcessor := thrift.NewTMultiplexedProcessor()
	mutiProcessor.RegisterProcessor("account", processor)
	transportFactory := NewTransportFactory()
	protocolFactory := NewProtocolFactory()

	server := thrift.NewTSimpleServer4(mutiProcessor, transport, transportFactory, protocolFactory)
	fmt.Println("Running at:", ":"+port)
	server.Serve()
}
func (s *ThriftStarter) Stop(ctx base.StarterContext) {}
func (s *ThriftStarter) StartBlocking() bool          { return true }
